package gl.java.game;

import com.jsoniter.JsonIterator;
import gl.java.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Test {
    static Logger log = LoggerFactory.getLogger(Test.class);
    private static long id;

    public static class Task implements Runnable {
        public String name;
        public int count = 0;
        public long lastTime = System.currentTimeMillis();

        public Task(String name) {
            this.name = name;
        }

        public Task() {
        }

        @Override
        public void run() {

            if (count >= 1000) {
                log.info("{} timer:{}", name, (System.currentTimeMillis() - lastTime));
                count = 0;
                lastTime = System.currentTimeMillis();
            } else {
                count++;
            }
//                log.warn(" run {}", count);
        }
    }


    public static void main(String[] args) {
        final GameEngine eg = GameEngine.getInstance();
        log.info("go!!!!!!!!!");
        id = eg.setInterval(new Task("custom"), 1);
        startNetWork(eg);
        eg.setNetWorkEventReceiver(new NetEventReceiver() {
            int count = 0;
            long lastTime = System.nanoTime();

            @Override
            public void onReceiver(NetEvent netEvent) {

                JsonUtil.fromJson2((String) netEvent.frame, Task.class);
//                JsonUtil.fromJson((String) netEvent.frame, Task.class);
                if (count >= 1000 * 10000) {
                    log.warn("recv take time {}", (System.nanoTime() - lastTime) / 1000000);
                    eg.clearInterval(id);
                    eg.stop();
                }
                count++;
            }
        });

    }

    private static void startNetWork(GameEngine eg) {
        Thread thread = new Thread() {

            @Override
            public void run() {
                int count = 0;
                long x = System.nanoTime();
//                int max = 10000 * 10000;
                int max = 1000 * 10000;
                while (count <= max) {
                    count++;
//                    log.info("==========net work " + count);
                    String a1 = JsonUtil.toString2(new Task("a"));
//                    JsonUtil.fromJson2(a1, Task.class);
                    eg.addNetWorkEvent(new NetEvent(null, a1));//有锁操作.
//                    eg.addNetWorkEvent(new NetEvent(null, JsonUtil.toString(new Task("a"))));
                }
                log.warn("push net event take:{} ms", (System.nanoTime() - x) / 1000000);
            }
        };
        thread.start();
    }
}
